﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using PokerServerWebService.BusinessEntities;
using System.Data.SqlClient;
using System.Diagnostics;
using PokerServerWebService.DataAccess.SQLServer;

namespace PokerServerWebService.DataAccess
{
    /// <summary>
    /// Respository that lets you find CASINO_USER_MONEY in the
    /// CRM database.
    /// </summary>
    public class CASINO_USER_MONEYRepository : Repository<CASINO_USER_MONEY>
    {
        private string databaseName;

        public CASINO_USER_MONEYRepository(string databaseName)
            : base(databaseName)
        {
            this.databaseName = databaseName;
        }
        

		public CASINO_USER_MONEY GetPlayerMoney(System.Int32 id)
        {
            ISelectionFactory<System.Int32> selectionFactory = new GetPlayerMoneySelectionFactory();
            
            try
            {
				return base.FindOne(selectionFactory, new GetPlayerMoneyFactory(), id);
			}
            catch (SqlException ex)
            {
                HandleSqlException(ex, selectionFactory);
            }
            
			return new CASINO_USER_MONEY();
        }

        public void Save(CASINO_USER_MONEY cASINO_USER_MONEY)
        {
            CASINO_USER_MONEYUpdateFactory updateFactory = new CASINO_USER_MONEYUpdateFactory();
            try
            {
                base.Save(updateFactory, cASINO_USER_MONEY);
            }
            catch (SqlException ex)
            {
                HandleSqlException(ex, updateFactory);
            }
        }

        private void HandleSqlException(SqlException ex, IDbToBusinessEntityNameMapper mapper)
        {
            if(ex.Number == ErrorCodes.SqlUserRaisedError)
            {
                switch(ex.State)
                {
                    case ErrorCodes.ValidationError:
                        string[] messageParts = ex.Errors[0].Message.Split(':');
                        throw new RepositoryValidationException(
                            mapper.MapDbParameterToBusinessEntityProperty(messageParts[0]),
                            messageParts[1], ex);

                    case ErrorCodes.ConcurrencyViolationError:
                        throw new ConcurrencyViolationException(ex.Message, ex);

                }
            }

            throw new RepositoryFailureException(ex);
        }
    }
}

